<template>
  <div class="chat-container">
    <header class="chat-header">
      <button @click="goBack" class="back-btn">&lt; 返回</button>
      <h1 class="chat-title">AI聊天助手</h1>
      <div class="header-actions">
        <button class="new-chat-btn" @click="startNewChat">+ 新聊天</button>
      </div>
    </header>

    <!-- 未开始聊天状态 -->
    <div v-if="chatState === 'not-started'" class="not-started-state">
      <div class="welcome-message">
        <h2>欢迎使用AI聊天助手</h2>
        <p>开始与AI对话，获取智能解答和帮助</p>
        <button @click="startNewChat" class="start-chat-btn">开始聊天</button>
      </div>
    </div>

    <!-- 聊天中状态 -->
    <div v-else-if="chatState === 'chatting'" class="chatting-state">
      <div class="message-list">
        <div v-for="(message, index) in messages" :key="index" class="message-item">
          <div :class="['message-bubble', message.sender === 'user' ? 'user-message' : 'ai-message']">
            <div class="message-content">{{ message.content }}</div>
            <div class="message-time">{{ message.time }}</div>
          </div>
        </div>
        <div v-if="loading" class="loading-indicator">
          <div class="dot-pulse"></div>
        </div>
      </div>

      <div class="input-area">
        <textarea
          v-model="userInput"
          @keydown.enter.prevent="sendMessage"
          placeholder="输入消息..."
          :disabled="loading"
        ></textarea>
        <button @click="sendMessage" :disabled="!userInput.trim() || loading" class="send-btn">发送</button>
      </div>
    </div>

    <!-- 聊天记录状态 -->
    <div v-else-if="chatState === 'history'" class="history-state">
      <h2 class="history-title">聊天记录</h2>
      <div class="history-list">
        <div v-for="(history, index) in chatHistory" :key="index" class="history-item" @click="loadChat(history.id)">
          <div class="history-title">{{ history.title }}</div>
          <div class="history-time">{{ history.time }}</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default { name: 'ChatView' }
</script>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';


const router = useRouter();
const route = useRoute();

// 聊天状态: 'not-started', 'chatting', 'history'
const chatState = ref('not-started');
const messages = ref([]);
const userInput = ref('');
const loading = ref(false);
const chatHistory = ref([]);

onMounted(() => {
  // 检查登录状态
  const isLoggedIn = localStorage.getItem('isLoggedIn');
  if (!isLoggedIn) {
    router.push('/login');
    return;
  }

  // 加载聊天历史
  loadChatHistory();

  // 如果有chatId参数，加载对应聊天
  const chatId = route.params.chatId;
  if (chatId) {
    loadChat(chatId);
  }
});

// 加载聊天历史
const loadChatHistory = () => {
  // 模拟聊天历史数据
  chatHistory.value = [
    {
      id: 1,
      title: '关于AI技术的讨论',
      time: '今天 10:30',
      messages: [
        { sender: 'user', content: '什么是人工智能？', time: '10:30' },
        { sender: 'ai', content: '人工智能是计算机科学的一个分支...', time: '10:31' },
        { sender: 'user', content: '它有哪些应用领域？', time: '10:32' },
        { sender: 'ai', content: '人工智能的应用领域非常广泛...', time: '10:33' }
      ]
    },
    {
      id: 2,
      title: '项目规划咨询',
      time: '昨天 16:45',
      messages: [
        { sender: 'user', content: '如何规划一个Vue项目？', time: '16:45' },
        { sender: 'ai', content: '规划Vue项目需要考虑以下几个方面...', time: '16:46' }
      ]
    }
  ];
};

// 加载指定聊天
const loadChat = (chatId) => {
  const chat = chatHistory.value.find(item => item.id === chatId);
  if (chat) {
    messages.value = chat.messages;
    chatState.value = 'chatting';
  }
};

// 开始新聊天
const startNewChat = () => {
  messages.value = [];
  chatState.value = 'chatting';
};

// 返回个人中心
const goBack = () => {
  router.push('/personal-center');
};

// 发送消息
const sendMessage = async () => {
  const content = userInput.value.trim();
  if (!content) return;

  // 添加用户消息
  const time = new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  messages.value.push({
    sender: 'user',
    content,
    time
  });

  userInput.value = '';
  loading.value = true;

  try {
    // 模拟调用DeepSeekR1 API
    // 实际项目中替换为真实API地址
    const response = await new Promise(resolve => {
      setTimeout(() => {
        resolve({
          data: {
            reply: '这是AI的回复内容。在实际应用中，这里会显示来自DeepSeekR1 API的实时响应。你可以继续提问，我会尽力帮助你。'
          }
        });
      }, 1500);
    });

    // 添加AI回复
    messages.value.push({
      sender: 'ai',
      content: response.data.reply,
      time: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
    });
  } catch (error) {
    messages.value.push({
      sender: 'ai',
      content: '抱歉，获取回复失败，请稍后再试。',
      time: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
    });
  } finally {
    loading.value = false;
    // 滚动到底部
    scrollToBottom();
  }
};

// 滚动到消息底部
const scrollToBottom = () => {
  setTimeout(() => {
    const messageList = document.querySelector('.message-list');
    if (messageList) {
      messageList.scrollTop = messageList.scrollHeight;
    }
  }, 100);
};
</script>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  max-width: 800px;
  margin: 0 auto;
  border-left: 1px solid #eee;
  border-right: 1px solid #eee;
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem;
  border-bottom: 1px solid #eee;
  background-color: white;
}

.back-btn {
  background: none;
  border: none;
  font-size: 1.2rem;
  cursor: pointer;
  color: #666;
  padding: 0.5rem;
}

.chat-title {
  margin: 0;
  font-size: 1.2rem;
  color: #333;
}

.header-actions {
  display: flex;
  gap: 0.5rem;
}

.new-chat-btn {
  padding: 0.5rem 1rem;
  background-color: #4285f4;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 0.9rem;
}

/* 未开始聊天状态 */
.not-started-state {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  padding: 2rem;
  text-align: center;
}

.welcome-message h2 {
  margin-bottom: 1rem;
  color: #333;
}

.welcome-message p {
  color: #666;
  margin-bottom: 2rem;
}

.start-chat-btn {
  padding: 0.8rem 1.5rem;
  background-color: #4285f4;
  color: white;
  border: none;
  border-radius: 5px;
  font-size: 1rem;
  cursor: pointer;
}

/* 聊天中状态 */
.chatting-state {
  display: flex;
  flex-direction: column;
  flex: 1;
}

.message-list {
  flex: 1;
  padding: 1rem;
  overflow-y: auto;
  background-color: #f9f9f9;
}

.message-item {
  margin-bottom: 1rem;
  display: flex;
}

.user-message {
  justify-content: flex-end;
}

.ai-message {
  justify-content: flex-start;
}

.message-bubble {
  max-width: 70%;
  padding: 0.8rem 1rem;
  border-radius: 10px;
  position: relative;
}

.user-message .message-bubble {
  background-color: #4285f4;
  color: white;
}

.ai-message .message-bubble {
  background-color: white;
  border: 1px solid #eee;
  color: #333;
}

.message-time {
  font-size: 0.7rem;
  margin-top: 0.3rem;
  opacity: 0.8;
  text-align: right;
}

.loading-indicator {
  display: flex;
  justify-content: flex-start;
  padding: 1rem;
}

.dot-pulse {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background-color: #4285f4;
  animation: dotPulse 1.5s infinite ease-in-out;
}

@keyframes dotPulse {
  0%, 100% { transform: scale(0); }
  50% { transform: scale(1); }
}

.input-area {
  display: flex;
  padding: 1rem;
  border-top: 1px solid #eee;
  background-color: white;
}

textarea {
  flex: 1;
  padding: 0.8rem;
  border: 1px solid #ddd;
  border-radius: 5px;
  resize: none;
  height: 50px;
  font-size: 1rem;
}

.send-btn {
  margin-left: 0.5rem;
  padding: 0 1.5rem;
  background-color: #4285f4;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.send-btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

/* 聊天记录状态 */
.history-state {
  flex: 1;
  padding: 1rem;
  overflow-y: auto;
}

.history-title {
  margin-top: 0;
  color: #333;
  padding-bottom: 1rem;
  border-bottom: 1px solid #eee;
}

.history-list {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.history-item {
  padding: 1rem;
  border: 1px solid #eee;
  border-radius: 5px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.history-item:hover {
  background-color: #f5f5f5;
}

.history-item .history-title {
  font-weight: 500;
  margin-bottom: 0.25rem;
  padding-bottom: 0;
  border-bottom: none;
}

.history-item .history-time {
  font-size: 0.8rem;
  color: #666;
}
</style>